/**
 * 
 */
package in.smartbillpay.web.services;
import in.smartbillpay.web.dao.UserDao;
import in.smartbillpay.web.models.SBPUser;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author ADIMBLE
 *
 */
@Service
@Transactional(readOnly = true)
public class UserServiceImpl implements UserService {
	private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	
	@Autowired
	private UserDao userDao;

	
	/**
	 * @return the userDao
	 */
	public UserDao getUserDao() {
		return userDao;
	}

	public SBPUser getUserById(int id) {
		return getUserDao().getUserById(id);
	}

	public List<SBPUser> getUserByName(String userName) {
		return getUserDao().getUserByName(userName);
	}

	public SBPUser saveOrUpdate(SBPUser user) {
		return getUserDao().saveOrUpdate(user);
	}

	/**
	 * loadUserByUsername() is used by spring security framework to authenticate/authorize the user
	 */
	
	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException {
		List<SBPUser> users = getUserDao().getUserByName(userName);
		if(users.size() == 0){
			logger.info("user not found in database -" + userName);
			
			throw new UsernameNotFoundException(userName + " not found");
		}
		else {
			
			logger.info("found the user in database -" + userName);
			logger.info("user password is -" + users.get(0).getPassword());
			return users.get(0);
		}
		
	}

	

}
